package com.office.util;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;

import java.io.File;


/**
 * office系列组件转pdf*
 * @author tianyf
 */
public class OfficeTransitionPdfUtil {

    /**
     * 本地ip*
     */

    private static final String connectIp = "localhost";

    private static final Integer connectPort = 8100;

    private static final String pdfUrl = "C:\\testFile\\pdfFile\\";

    private static final String suffix = ".pdf";

    /**
     * 将office 转换为  pdf 工具类*
     * @param file
     * @return
     */
    public static File officeTranstionPdf(File file){
        OpenOfficeConnection connection = null;
        File pdfFile = null;
        try {

            connection = new SocketOpenOfficeConnection(connectIp, connectPort);
            connection.connect();

            DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);

            long startMs = System.currentTimeMillis();
            pdfFile = new File(pdfUrl + file.getName() + suffix);
            converter.convert(file , pdfFile);
            long endMs = System.currentTimeMillis();
            System.out.println("convert success, spend time is : {} ms."+(endMs-startMs));
        } catch (Exception e) {
            System.out.println(e.fillInStackTrace());
        } finally {
            if(connection != null) {
                connection.disconnect();
                System.out.println("connection disconnected. ");
            }
        }
        return pdfFile;
    }
}
